<template>
  <div v-loading="loading" style="background-color:#fff;padding:10px;">
    <el-row>
      <el-card>
        <div slot="header">
          <span>选择问卷</span>
        </div>
        <div>
          <el-select v-model="selQuestion" size="small">
            <el-option v-for="questionnaire in questionnaireList" :value="questionnaire.id" :key="questionnaire.id"
                       :label="questionnaire.title"></el-option>
          </el-select>
          <el-button size="small" type="primary" @click="btnShowAddDialog" style="margin-left:15px;">运行新实例</el-button>
        </div>
      </el-card>
    </el-row>
    <el-row v-if="selQa" style="margin-top:10px;">
      <el-card>
        <div slot="header">
          <span>{{selQa.title}} 实例列表</span>
        </div>
        <div>
          <el-table size="small" :data="instanceList" :cell-style="{textAlign:'center'}" :header-cell-style="{textAlign:'center'}">
            <el-table-column type="index"></el-table-column>
            <el-table-column label="标题">
              <template slot-scope="scope">
                <el-input size="small" @keydown.native.prevent.enter="enterKey"
                          @change="checkInput(scope.row,$event)" @blur="exitEdit(scope.row)" v-if="scope.row.edit" v-model="scope.row.title"></el-input>
                <span v-else @click="clickTitle(scope.row)">{{scope.row.title}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="created" label="创建时间" :formatter="dateFormatter"></el-table-column>
            <el-table-column label="可重复">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.repeatable" @change="enableSwitch(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.enable" @change="enableSwitch(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="operater" label="创建者"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleUpdate(scope.$index, scope.row)">更新
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-row>
    <el-dialog title="新建问卷实例" :visible.sync="showAddDialog">
      <div style="margin:0 20px;">
        <el-form size="mini" label-width="100px;">
          <el-form-item label="选择问卷：">
            <el-select v-model="selQuestion" size="small">
              <el-option v-for="questionnaire in questionnaireList" :value="questionnaire.id" :key="questionnaire.id"
                         :label="questionnaire.title"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="可否重复：">
            <el-switch v-model="addForm.repeatable"></el-switch>
          </el-form-item>
          <el-form-item label="实例标题：">
            <el-input v-model="addForm.title"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btnSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {mapGetters, mapActions} from 'vuex'
  import dateFormat from '@/common/date-formater'

  export default {
    name: "qa-instance-manage",
    props: ['page'],
    data() {
      return {
        loading:false,
        questionnaireList: null,
        instanceList: null,
        selQuestion: null,
        showAddDialog:false,
        addForm:{
          repeatable:false,
          title:''
        }
      }
    },
    computed: {
      selQa() {
        if (this.selQuestion) {
          return this.questionnaireList.find(qa => qa.id === this.selQuestion)
        } else return null
      }
    },
    watch: {
      selQuestion(nId, oId) {
        if (nId){
          this.getInstanceById(nId)
          if(this.addForm && this.addForm.title === '')
            this.addForm.title = this.selQa.title
        }
      }
    },
    created() {

    },
    mounted() {
      //加载问卷
      this.fetch({ name: "getQuestionnaireList" })
        .then((res) => {
          if (res.errCode) {
            this.$message({ type: 'info', message: res.errMsg })
          } else {
            this.questionnaireList = res
          }
        })
        .catch((err) => {
          console.log(err)
          this.$message({ type: 'error', message: "服务器错误" })
        })
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      enterKey(event){
        //console.log(event)
        event.target.blur()
      },
      exitEdit(row){
        row.edit = !row.edit
        let params = {
          instanceId:row.id,
          title:row.title
        }
        this.updateInstance(params,(res)=>{
          this.getInstanceById(this.selQuestion)
        })
      },
      clickTitle(row){
        //console.log(row)
        if(row.edit === undefined)
          Vue.set(row,'edit',true)
        else
          row.edit = !row.edit
      },
      handleUpdate(index, row) {
        this.$confirm('更新操作会更新问卷的新版本，你确定更新？?')
          .then(()=>{
            //resetInstance
            this.fetch({name:'resetInstance',data:{instanceId:row.id}})
              .then(res=>{
                if (res.errCode) {
                  this.$message({ type: 'error', message: res.errMsg })
                } else {
                  //重新加载列表
                  this.getInstanceById(this.selQuestion)
                }
              })
              .catch(err=>{
                console.log(err)
                this.$message({ type: 'error', message: "服务器错误" })
              })
              .finally(()=>{
                this.loading = false
              })
          }).catch(()=>{})//取消不操作
      },
      handleDelete(index, row) {
        this.$confirm('确认删除?')
          .then(() => {
            this.loading = true
            this.fetch({name:'deleteInstance',data:{instanceId:row.id}})
              .then(res=>{
                if (res.errCode) {
                  this.$message({ type: 'error', message: res.errMsg })
                } else {
                  //重新加载列表
                  this.getInstanceById(this.selQuestion)
                }
              })
              .catch(err=>{
                console.log(err)
                this.$message({ type: 'error', message: "服务器错误" })
              })
              .finally(()=>{
                this.loading = false
              })
          })
          .catch(() => {
          })
      },
      btnSubmit(){
        this.loading=true
        this.fetch({name:'createInstance',data:{...this.addForm,qaId:this.selQuestion}})
          .then(res=>{
            if (res.errCode) {
              this.$message({ type: 'error', message: res.errMsg })
            } else {
              //重新加载列表
              this.getInstanceById(this.selQuestion)
            }
          })
          .catch(err=>{
            console.log(err)
            this.$message({ type: 'error', message: "服务器错误" })
          })
          .finally(()=>{
            this.loading=false
            this.showAddDialog=false
          })
      },
      btnShowAddDialog(){
        this.addForm = {
          repeatable:false,
          title:this.selQa ? this.selQa.title:''
        }
        this.showAddDialog = true;
      },
      enableSwitch(row){
        //console.log(row)
        let params = {
          instanceId:row.id,
            repeatable:row.repeatable,
            enable:row.enable,
            title:row.title
        }
        this.updateInstance(params)
      },
      updateInstance(data,cb){
        this.loading=true
        this.fetch({name:'updateInstance',data})
          .then(res=>{
            if (res.errCode) {
              this.$message({ type: 'error', message: res.errMsg })
            } else {
              //调用回调
              if(cb) cb(res)
            }
          })
          .catch(err=>{

          })
          .finally(()=>{
            this.loading=false
          })
      },
      dateFormatter(row,column,cellValue){
        return dateFormat.formatDatetime(row.created)
      },
      getInstanceById(id) {
        this.fetch({ name: 'listInstance', data: { qaId: id } })
          .then(res => {
            if (res.errCode) {
              this.$message({ type: 'info', message: res.errMsg })
            } else {
              console.log(res)
              this.instanceList = res
            }
          }).catch(err => {
          console.log(err)
          this.$message({ type: 'error', message: "服务器错误" })
        })
      }
    }
  }
</script>

<style lang="scss">

</style>
